package com.sunda.spmsorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunda.spmsorder.entity.OrderWerks;
import com.sunda.spmsorder.entity.OrderWerksDtl;
import com.sunda.spmsorder.entity.OrderWorkshop;
import com.sunda.spmsorder.mapper.OrderLogMapper;
import com.sunda.spmsorder.mapper.OrderWerksDtlMapper;
import com.sunda.spmsorder.mapper.OrderWerksMapper;
import com.sunda.spmsorder.mapper.OrderWorkshopMapper;
import com.sunda.spmsorder.service.IOrderWerksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sunda.spmscommon.Constans.*;

/**
 * <p>
 * 工厂请购单 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-02-05
 */
@Service
public class OrderWerksServiceImpl extends ServiceImpl<OrderWerksMapper, OrderWerks> implements IOrderWerksService {

    @Autowired
    OrderWerksMapper orderWerksMapper;

    @Autowired
    OrderWerksDtlMapper orderWerksDtlMapper;

    @Autowired
    OrderWorkshopMapper orderWorkshopMapper;

    @Autowired
    OrderLogMapper orderLogMapper;

    /** 根据工厂代码 和 工厂请购单状态，查询工厂请购单表头信息；状态字段可选输入； */
    @Override
    public IPage<OrderWerks> getOrderWerksByWerks(Page<OrderWerks> page, String werks,
    String spmsStatus, String spmsId, String urgencyDegree, String dateRequiredStart, 
    String dateRequiredEnd, String applicationDateStart, String applicationDateEnd) {

        QueryWrapper<OrderWerks> qw = new QueryWrapper<OrderWerks>();
        if (StringUtils.isNotEmpty(werks)){
            String[] werksArray=werks.split(",");
            if(werksArray.length>0){
                qw.in("WERKS",werksArray);
            }
        }
        if (StringUtils.isNotEmpty(spmsStatus)){
            qw.eq("STATUS", spmsStatus);
        } else {
            /** 默认查询工厂请购单，状态传空时不查关闭状态单据 */
            qw.ne("STATUS", "0");
        }
        if (StringUtils.isNotEmpty(spmsId)){
            qw.eq("SPMS_ID", spmsId);
        }
        if (StringUtils.isNotEmpty(urgencyDegree)){
            qw.eq("URGENCY", urgencyDegree);
        }
        if (StringUtils.isNotEmpty(dateRequiredStart)){
            qw.ge("DATE_REQUIRED", dateRequiredStart);
        }
        if (StringUtils.isNotEmpty(dateRequiredEnd)){
            qw.le("DATE_REQUIRED", dateRequiredEnd);
        }
        if (StringUtils.isNotEmpty(applicationDateStart)){
            qw.ge("APPLICATION_DATE", applicationDateStart);
        }
        if (StringUtils.isNotEmpty(applicationDateEnd)){
            qw.le("APPLICATION_DATE", applicationDateEnd);
        }
        qw.orderByDesc("SPMS_ID");
        return orderWerksMapper.selectPage(page, qw);
    }

    /** 获取工厂请购单行项目信息 */
    @Override
    public Map<String, Object> getOrderWerksDtl(int pageNo, int pageSize, String spmsId) {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> mapList = orderWerksMapper.getOrderWerksDtl(spmsId);
        PageInfo<Map<String, Object>> pageData = new PageInfo<>(mapList);
        Map<String,Object> pageInfo = new HashMap<>();
        pageInfo.put("records", pageData.getList());
        pageInfo.put("total", pageData.getTotal());
        pageInfo.put("size", pageData.getSize());
        pageInfo.put("current", pageData.getPageNum());
        pageInfo.put("pages", pageData.getPages());
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> getOrderWerksDtl2(String spmsId) {
        if (StringUtils.isEmpty(spmsId)){
            return null;
        }
        return orderWerksMapper.getOrderWerksDtl(spmsId);
    }

    @Override
    public List<Map<String, Object>> getOrderWerksDtlWithInventory(String spmsId) {
        if (StringUtils.isEmpty(spmsId)){
            return null;
        }
        return orderWerksMapper.getOrderWerksDtlWithInventory(spmsId);
    }

    /** 根据用户传入信息，创建工厂请购单和工厂请购单详情
     * {
     * 	"orderWerks": {
     * 		"spmsId": "",
     * 		"uuid": "",
     * 		"urgency": "0",
     * 		"applicationDate": "2020-02-05",
     * 		"dateRequired": "2020-07-01",
     * 		"subject": "GH01-2020XXX工厂请购单",
     * 		"status": "1",
     * 		"userId": "20002",
     * 		"lastName": "20002",
     * 		"werks": "GH01",
     * 		"workshopCode": "",
     * 		"deptId": "11",
     * 		"positionId": "12",
     * 		"company": "company",
     * 		"branchPoint": "branch point",
     * 		"branchLine": "branch line",
     * 		"purchaseLocation": "0",
     * 		"justification": "请购原因",
     * 		"projectCode": "1111",
     * 		"estimateCost": 100000,
     * 		"projectType": "1",
     * 		"projectStatus": "1",
     * 		"projectCategory": "1",
     * 		"shippingType": "0",
     * 		"shippingFangshi": "",
     * 		"applicationType": "",
     * 		"deviceCategory": "",
     * 		"deviceType": "",
     * 		"materialCategory": "",
     * 		"approvalComments": "",
     * 		"oaId": "20002",
     * 		"oaProcessId": "",
     * 		"oaApprovalDate": "",
     * 		"fieldForOa": "",
     * 		"detailExplain": "",
     * 		"relevantProcess": "",
     * 		"relevantDocument": "",
     * 		"purchaseManager": "",
     * 		"costDeptId": "",
     * 		"costDeptName": "",
     * 		"deviceStatement": "",
     * 		"deviceAttachment": "",
     * 		"comments": "",
     * 		"oaBianhao": "",
     * 		"relevantDepartment": "",
     * 		"attachmentList": ""
     *        },
     * 	"orderWerksDtlList": [{
     * 			"spmsId": "",
     * 			"spmsWsId": "GH011002-20210202-0002",
     * 			"rowIdWerks": 10,
     * 			"rowIdWs": 10,
     * 			"uuid": "",
     * 		"orderWorkshopUuid": "3d6e22392dce4691a8a62c27d7da3132"
     *        },
     *        {
     * 			"spmsId": "",
     * 			"spmsWsId": "GH011002-20210202-0002",
     * 			"rowIdWerks": 20,
     * 			"rowIdWs": 20,
     * 			"uuid": "",
     * 		"orderWorkshopUuid": "3d6e22392dce4691a8a62c27d7da3132"
     *        }
     * 	]
     * }
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Boolean addOrderWerks(JSONObject doc, String uuid) {
        if (!doc.containsKey("orderWerks") || doc.getString("orderWerks").length() == 0){
            return false;
        }
        if (StringUtils.isEmpty(doc.getJSONObject("orderWerks").getString("werks")) ||
                StringUtils.isEmpty(doc.getJSONObject("orderWerks").getString("applicationDate"))){
            return false;
        }
        if (!doc.containsKey("orderWerksDtlList") || doc.getJSONArray("orderWerksDtlList").size() == 0){
            return false;
        }
        try {
            String userId = doc.getJSONObject("orderWerks").getString("userId");
            //String status = doc.getJSONObject("orderWerks").getString("status");
            JSONArray orderWerksDtlDoc = doc.getJSONArray("orderWerksDtlList");

            /** 校验车间请购单是否都处于 已提交-2 状态，只要有一个不是状态 2 则返回错误。 */
            if (!checkOrderWorkshopSubmit(orderWerksDtlDoc)){
                return false;
            }

            JSONObject orderWerksDoc = doc.getJSONObject("orderWerks");
            /** 创建工厂请购单表头 */
            createOrderWerks(orderWerksDoc, uuid);
            System.err.println("============ 创建工厂请购单成功 =============");


            /** 创建工厂请购单行项目 —— 同时更新车间请购单状态、增加操作日志 */
            createOrderWerksDtl(userId, orderWerksDtlDoc, uuid);
            System.err.println("============ 创建工厂请购单行项目成功 =============");

            return true;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    /** 合单车间请购单审批之前，校验被审批的所有 车间请购单 状态是否都为 2-已提交；如果有单据状态不为 2 则返回错误信息表示创建工厂请购单失败； */
    synchronized Boolean checkOrderWorkshopSubmit(JSONArray orderWerksDtlDoc){
        Boolean result = true;
        for (int i = 0; i < orderWerksDtlDoc.size(); i ++){
            String orderWorkshopUuid = orderWerksDtlDoc.getJSONObject(i).getString("orderWorkshopUuid");
            if (!"2".equals(this.baseMapper.getOrderWorkshopStatus(orderWorkshopUuid))){
                result = false;
            }
            break;
        }
        return result;
    }

    /**
     * {
     * 		"spmsId": "",
     * 		"uuid": "",
     * 		"urgency": "0",
     * 		"applicationDate": "2020-02-05",
     * 		"dateRequired": "2020-07-01",
     * 		"subject": "GH01-2020XXX工厂请购单",
     * 		"status": "1",
     * 		"userId": "20002",
     * 		"lastName": "20002",
     * 		"werks": "GH01",
     * 		"workshopCode": "",
     * 		"deptId": "11",
     * 		"positionId": "12",
     * 		"company": "company",
     * 		"branchPoint": "branch point",
     * 		"branchLine": "branch line",
     * 		"purchaseLocation": "0",
     * 		"justification": "请购原因",
     * 		"projectCode": "1111",
     * 		"estimateCost": 100000,
     * 		"projectType": "1",
     * 		"projectStatus": "1",
     * 		"projectCategory": "1",
     * 		"shippingType": "0",
     * 		"shippingFangshi": "",
     * 		"applicationType": "",
     * 		"deviceCategory": "",
     * 		"deviceType": "",
     * 		"materialCategory": "",
     * 		"approvalComments": "",
     * 		"oaId": "",
     * 		"oaProcessId": "",
     * 		"oaApprovalDate": "",
     * 		"fieldForOa": "",
     * 		"detailExplain": "",
     * 		"relevantProcess": "",
     * 		"relventDocument": "",
     * 		"purchaseManager": "",
     * 		"costDeptId": "",
     * 		"costDeptName": "",
     * 		"deviceStatement": "",
     * 		"deviceAttachment": "",
     * 		"comments": "",
     * 		"oaBianhao": "",
     * 		"relventDepartment": "",
     * 		"attachmentList": ""
     *}
     * @param doc
     * @param uuid
     * @return
     */
    public int createOrderWerks(JSONObject doc, String uuid){
        OrderWerks orderWerks = new OrderWerks();
        orderWerks.setSpmsId(null);
        orderWerks.setUuid(uuid);
        orderWerks.setUrgency(doc.getString("urgency"));
        orderWerks.setApplicationDate(doc.getString("applicationDate"));
        orderWerks.setDateRequired(doc.getString("dateRequired"));
        orderWerks.setSubject(doc.getString("subject"));
        orderWerks.setStatus(doc.getString("status"));
        orderWerks.setUserId(doc.getString("userId"));
        orderWerks.setLastName(doc.getString("lastName"));
        orderWerks.setWerks(doc.getString("werks"));
        orderWerks.setWorkshopCode(doc.getString("workshopCode"));
        orderWerks.setDeptId(doc.getString("deptId"));
        orderWerks.setPositionId(doc.getString("positionId"));
        orderWerks.setCompany(doc.getString("company"));
        orderWerks.setBranchPoint(doc.getString("branchPoint"));
        orderWerks.setBranchLine(doc.getString("branchLine"));
        orderWerks.setPurchaseLocation(doc.getString("purchaseLocation"));
        orderWerks.setJustification(doc.getString("justification"));
        orderWerks.setProjectCode(doc.getString("projectCode"));
        orderWerks.setEstimateCost(Double.parseDouble(doc.getString("estimateCost")));
        orderWerks.setProjectType(doc.getString("projectType"));
        orderWerks.setProjectStatus(doc.getString("projectStatus"));
        orderWerks.setProjectCategory(doc.getString("projectCategory"));
        orderWerks.setShippingType(doc.getString("shippingType"));
        orderWerks.setShippingFangshi(doc.getString("shippingFangshi"));
        orderWerks.setApplicationType(doc.getString("applicationType"));
        orderWerks.setDeviceCategory(doc.getString("deviceCategory"));
        orderWerks.setDeviceType(doc.getString("deviceType"));
        orderWerks.setMaterialCategory(doc.getString("materialCategory"));
        orderWerks.setApprovalComments(doc.getString("approvalComments"));
        orderWerks.setOaId(doc.getString("oaId"));
        orderWerks.setOaProcessId(doc.getString("oaProcessId"));
        orderWerks.setFieldForOa(doc.getString("fieldForOa"));
        orderWerks.setDetailExplain(doc.getString("detailExplain"));
        orderWerks.setRelevantProcess(doc.getString("relevantProcess"));
        orderWerks.setRelevantDocument(doc.getString("relevantDocument"));
        orderWerks.setPurchaseManager(doc.getString("purchaseManager"));
        orderWerks.setCostDeptId(doc.getString("costDeptId"));
        orderWerks.setCostDeptName(doc.getString("costDeptName"));
        orderWerks.setDeviceStatement(doc.getString("deviceStatement"));
        orderWerks.setDeviceAttachment(doc.getString("deviceAttachment"));
        orderWerks.setComments(doc.getString("comments"));
        orderWerks.setRelevantDepartment(doc.getString("relevantDepartment"));
        orderWerks.setAttachmentList(doc.getString("attachmentList"));
        /** 添加工厂请购单日志信息 */
        addOrderLog(doc.getString("userId"),  CREATE_ORDER_WERKS, uuid);
        return orderWerksMapper.createOrderWerks(orderWerks);
    }

    /**
     *  [{
     * 			"spmsId": "",
     * 			"spmsWsId": "GH011002-20210202-0002",
     * 			"rowIdWerks": 10,
     * 			"rowIdWs": 10,
     * 			"uuid": "",
     * 			"orderWorkshopUuid": "3d6e22392dce4691a8a62c27d7da3132"
     *                },
     *        {
     * 			"spmsId": "",
     * 			"spmsWsId": "GH011002-20210202-0002",
     * 			"rowIdWerks": 20,
     * 			"rowIdWs": 20,
     * 			"uuid": "",
     * 			"orderWorkshopUuid": "3d6e22392dce4691a8a62c27d7da3132"
     *        }
     * 	]
     *
     * @param array
     * @param uuid
     * @return
     */
    public int createOrderWerksDtl(String userId, JSONArray array, String uuid){
        int result = 0;
        Set set = new HashSet();
        if (array.size() > 0){
            for(int i = 0; i < array.size(); i++){
                JSONObject doc = array.getJSONObject(i);

                if (!set.contains(doc.getString("spmsWsId"))){
                    /** 4 - 机电主任审批通过提交OA */
                    updateOrderWorkshopStatus(doc.getString("spmsWsId"), "4");
                    addOrderLog(userId,  SUBMIT_OA, doc.getString("orderWorkshopUuid"));
                    set.add(doc.getString("spmsWsId"));
                }

                OrderWerksDtl orderWerksDtl = new OrderWerksDtl();
                //orderWerksDtl.setRowIdWerks(Integer.parseInt(doc.getString("rowIdWerks")));
                orderWerksDtl.setRowIdWerks((i + 1) * 10);
                orderWerksDtl.setSpmsWsId(doc.getString("spmsWsId"));
                orderWerksDtl.setRowIdWs(Integer.parseInt(doc.getString("rowIdWs")));
                orderWerksDtl.setUuid(uuid);
                result += orderWerksDtlMapper.createOrderWerksDtl(orderWerksDtl);
            }
        }
        return result;
    }

    public void updateOrderWorkshopStatus(String spmsWsId, String status){
        OrderWorkshop orderWorkshop = new OrderWorkshop();
        orderWorkshop.setStatus(status);
        System.out.println("======= 更新车间请购单表头 " + spmsWsId + " ======\n");
        orderWorkshopMapper.update(orderWorkshop, new QueryWrapper<OrderWorkshop>().eq("SPMS_WS_ID", spmsWsId));
    }

    public void addOrderLog(String userId, String comments, String uuid){
        //OrderLog orderLog = new OrderLog();
        System.out.println("======= 给车间请购单增加日志信息： " + userId + "，" + comments + "，" + uuid + " ======\n");
        orderLogMapper.insertOrderLog(userId, comments, uuid);
    }

    /**
     * {
     *           "spmsId": "GH01-2021-0004",
     *           "uuid": "4105e93ae4ca4105af571d13b94c7a2e",
     *           "urgency": "0",
     *           "applicationDate": "2021-02-24",
     *           "dateRequired": "2021-05-25",
     *           "subject": "GH01 - 20001 -2021-02-24",
     *           "status": "1",
     *           "userId": "20001",
     *           "lastName": "20001",
     *           "werks": "GH01",
     *           "workshopCode": "20001",
     *           "deptId": "123",
     *           "positionId": "11",
     *           "company": "company",
     *           "branchPoint": "12345",
     *           "branchLine": "123456",
     *           "purchaseLocation": null,
     *           "justification": null,
     *           "projectCode": null,
     *           "estimateCost": 0,
     *           "projectType": null,
     *           "projectStatus": null,
     *           "projectCategory": null,
     *           "shippingType": null,
     *           "shippingFangshi": null,
     *           "applicationType": null,
     *           "deviceCategory": null,
     *           "deviceType": null,
     *           "materialCategory": null,
     *           "approvalComments": null,
     *           "oaId": null,
     *           "oaProcessId": null,
     *           "oaApprovalDate": null,
     *           "fieldForOa": null,
     *           "detailExplain": null,
     *           "relevantProcess": null,
     *           "relevantDocument": null,
     *           "purchaseManager": null,
     *           "costDeptId": null,
     *           "costDeptName": null,
     *           "deviceStatement": null,
     *           "deviceAttachment": null,
     *           "comments": null,
     *           "oaBianhao": null,
     *           "relevantDepartment": null,
     *           "attachmentList": null,
     *           "createTime": "2021-02-24 01:48:35"
     *         }
     * @param doc
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderWerks(JSONObject doc, String userId) {
        try {
            /** 更新工厂请购单表头 */
            if (!doc.containsKey("spmsId") || doc.getString("spmsId").length() == 0){
                return 0;
            }
            String spmsId = doc.getString("spmsId");
            String status = doc.getString("status");
            OrderWerks orderWerks = new OrderWerks();
            orderWerks.setUrgency(doc.getString("urgency"));
            orderWerks.setDateRequired(doc.getString("dateRequired"));
            orderWerks.setSubject(doc.getString("subject"));
            orderWerks.setStatus(status);
            orderWerks.setUserId(doc.getString("userId"));
            orderWerks.setLastName(doc.getString("lastName"));
            //orderWerks.setWerks(doc.getString("werks"));
            orderWerks.setWorkshopCode(doc.getString("workshopCode"));
            orderWerks.setDeptId(doc.getString("deptId"));
            orderWerks.setPositionId(doc.getString("positionId"));
            orderWerks.setCompany(doc.getString("company"));
            orderWerks.setBranchPoint(doc.getString("branchPoint"));
            orderWerks.setBranchLine(doc.getString("branchLine"));
            orderWerks.setPurchaseLocation(doc.getString("purchaseLocation"));
            orderWerks.setJustification(doc.getString("justification"));
            orderWerks.setProjectCode(doc.getString("projectCode"));
            orderWerks.setEstimateCost(Double.parseDouble(doc.getString("estimateCost")));
            orderWerks.setProjectType(doc.getString("projectType"));
            orderWerks.setProjectStatus(doc.getString("projectStatus"));
            orderWerks.setProjectCategory(doc.getString("projectCategory"));
            orderWerks.setShippingType(doc.getString("shippingType"));
            orderWerks.setShippingFangshi(doc.getString("shippingFangshi"));
            orderWerks.setApplicationType(doc.getString("applicationType"));
            orderWerks.setDeviceCategory(doc.getString("deviceCategory"));
            orderWerks.setDeviceType(doc.getString("deviceType"));
            orderWerks.setMaterialCategory(doc.getString("materialCategory"));
            orderWerks.setApprovalComments(doc.getString("approvalComments"));
            orderWerks.setOaId(doc.getString("oaId"));
            orderWerks.setOaProcessId(doc.getString("oaProcessId"));
            orderWerks.setFieldForOa(doc.getString("fieldForOa"));
            orderWerks.setDetailExplain(doc.getString("detailExplain"));
            orderWerks.setRelevantProcess(doc.getString("relevantProcess"));
            orderWerks.setRelevantDocument(doc.getString("relevantDocument"));
            orderWerks.setPurchaseManager(doc.getString("purchaseManager"));
            orderWerks.setCostDeptId(doc.getString("costDeptId"));
            orderWerks.setCostDeptName(doc.getString("costDeptName"));
            orderWerks.setDeviceStatement(doc.getString("deviceStatement"));
            orderWerks.setDeviceAttachment(doc.getString("deviceAttachment"));
            orderWerks.setComments(doc.getString("comments"));
            orderWerks.setOaBianhao(StringUtils.isEmpty(doc.getString("oaBianhao")) ? null : doc.getString("oaBianhao"));
            orderWerks.setRelevantDepartment(doc.getString("relevantDepartment"));
            orderWerks.setAttachmentList(doc.getString("attachmentList"));

            /** 添加工厂请购单日志信息 */
            addOrderLog(userId,  UPDATE_ORDER_WERKS, doc.getString("uuid"));
            return orderWerksMapper.update(orderWerks, new QueryWrapper<OrderWerks>().eq("SPMS_ID", spmsId));
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    @Override
    public Map<String, Object> getOrderWerksDtlById(String spmsId) {
        Map<String, Object> map = new HashMap<>();
        if (spmsId != null && spmsId.length() > 0){

            OrderWerks orderWerks = orderWerksMapper.selectOne(new QueryWrapper<OrderWerks>().eq("SPMS_ID", spmsId));
            /** 将查出的 OrderWerks entity 转为 Map 再添加到 mapList 中 */
            map.put("orderWerks", JSON.parseObject(JSON.toJSONString(orderWerks), Map.class));

            map.put("orderWerksDtl", orderWerksMapper.getOrderWerksDtl(spmsId));

            map.put("orderLogList", orderLogMapper.getLogByOrderWerksId(spmsId));

        }
        return map;
    }

    @Override
    public void updateOrderWerksByUuid(String uuid, String oaBianhao) {
        OrderWerks orderWerks = new OrderWerks();
        orderWerks.setOaBianhao(oaBianhao);
        orderWerksMapper.update(orderWerks, new QueryWrapper<OrderWerks>().eq("UUID", uuid));
    }

    @Override
    public void updateOrderWerksStatusByUuid(String uuid, String status) {
        OrderWerks orderWerks = new OrderWerks();
        orderWerks.setStatus(status);
        orderWerksMapper.update(orderWerks, new QueryWrapper<OrderWerks>().eq("UUID", uuid));
    }

    @Override
    public String getSpmsIdByUuid(String uuid) {
        return orderWerksMapper.getSpmsIdByUuid(uuid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderWerksStatus(String userId, String oaBianhao, String oaStatus) {
        if (StringUtils.isEmpty(oaBianhao) || StringUtils.isEmpty(oaStatus)){
            return 0;
        }
        try {
            OrderWerks orderWerks = orderWerksMapper.selectOne(new QueryWrapper<OrderWerks>().eq("OA_BIANHAO", oaBianhao));
            if (orderWerks == null || orderWerks.toString().length() == 0){
                return 0;
            }
            if ("3".equals(orderWerks.getStatus())){
                return -2;  //已经审批通过了的，禁止重复提交审批
            }
            if ("S".equals(oaStatus)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String oaApprovalDate = sdf.format(new Date());
                orderWerks.setStatus("3"); //3 OA审批通过状态
                orderWerks.setOaApprovalDate(oaApprovalDate);
                int resp = orderWerksMapper.update(orderWerks, new QueryWrapper<OrderWerks>().eq("OA_BIANHAO", oaBianhao));
                /** 审批通过，添加工厂请购单日志信息 */
                addOrderLog(userId,  OA_APPROVED, orderWerks.getUuid());
                /** 应 SPMS 生产环境对 SRM 测试切换到 SPMS 生产环境对 SRM 生产环境需要，
                 * 提交OA日期早于 2021-07-12 00：00：00 的单据不推送到 SRM 生产环境，
                 * 7-12号0点以后的单据才需要提交到SRM生产环境；作出如下改动 ————20210713 */
                DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                if (fmt.parse(orderWerks.getApplicationDate()).getTime() - fmt.parse("2021-07-12").getTime() < 0){
                    addOrderLog(userId,  "OA审批通过不推送SRM", orderWerks.getUuid());
                    return -3;
                }
                return resp;
            }else {
                orderWerks.setStatus("4"); //4 OA审批不通过状态
                int resp = orderWerksMapper.update(orderWerks, new QueryWrapper<OrderWerks>().eq("OA_BIANHAO", oaBianhao));
                /** 审批不通过，添加工厂请购单日志信息 */
                addOrderLog(userId,  OA_REJECT, orderWerks.getUuid());
                return -1;
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    /** 根据工厂请购单uuid查询请购单提交SRM - ed64f63d663141028cad97a42510da89 */
    @Override
    public Map<String, Object> orderWerksToSrm(String uuid) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("Head", orderWerksMapper.orderWerksInfo(uuid));
            map.put("Items", orderWerksMapper.orderWerksDtlInfo(uuid));
            System.out.println("\n\n\n====orderWerksToSrm uuid====\n\n" + map);
            return map;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("e === " + e);
            return map;
        }
    }

    // oaBianhao = 945496
    @Override
    public Map<String, Object> orderWerksToSrm2(String oaBianhao) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("Head", orderWerksMapper.orderWerksInfo2(oaBianhao));
            map.put("Items", orderWerksMapper.orderWerksDtlInfo2(oaBianhao));
            //System.out.println("\n\n\n====orderWerksToSrm oaBianhao====\n\n" + map);
            return map;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("e === " + e);
            return map;
        }
    }

    @Override
    public OrderWerks getByOaBianhao(String oaBianhao) {
        if (StringUtils.isEmpty(oaBianhao)){
            return null;
        }
        return orderWerksMapper.selectOne(new QueryWrapper<OrderWerks>().eq("OA_BIANHAO", oaBianhao));
    }

    @Override
    public synchronized void  updateOrderWerksStatusByOaBianhao(String userId, String oaBianhao, String status) {
        OrderWerks orderWerks = orderWerksMapper.selectOne(new QueryWrapper<OrderWerks>().eq("OA_BIANHAO", oaBianhao));
        orderWerks.setStatus(status);
        orderWerksMapper.update(orderWerks, new QueryWrapper<OrderWerks>().eq("OA_BIANHAO", oaBianhao));
        if ("5".equals(status)){
            addOrderLog(userId,  SUBMIT_SRM, orderWerks.getUuid());
        }
        if ("8".equals(status)){
            addOrderLog(userId,  SUBMIT_SRM_ERROR, orderWerks.getUuid());
        }
    }

    /** 获取高频SKU报表/以工厂请购单为基准 */
    @Override
    public List<Map<String, Object>> getFrequencyMaterialNo(String werks, String materialNo, String beginDate, String endDate) {
        return this.baseMapper.getFrequencyMaterialNo(werks, materialNo, beginDate, endDate);
    }

    /** 根据 uuid 查找工厂请购单 */
    @Override
    public OrderWerks getByUuid(String uuid) {
        if (StringUtils.isEmpty(uuid)){
            return null;
        }
        return orderWerksMapper.selectOne(new QueryWrapper<OrderWerks>().eq("UUID", uuid));
    }
}



